<?php
/**
 * Created by PhpStorm.
 * User: vbao
 * Date: 2016/6/12
 * Time: 11:51
 */

namespace Home\Controller;
use QL\QueryList;
use Think\Controller;

class CreateController extends Controller
{

    public function _initialize()
    {
        set_time_limit(0);
        header("Content-type: text/html; charset=utf-8");

    }

    public $siteInfo; //网站信息

    /**
     * 翻译
     */
    public function transArticle(){

        $limit = 6;
        $articles = D('Article')->where('status=0')->limit($limit)->select();

        //实时显示提示信息 html
        $ii = 0;
        G('begin');
        showMsgHtml();
        showMsg("准备翻译文章!");

        foreach ($articles as $key =>$value){
            $ii++;
            $saveInfo['seo_keyword'] = translation($value['seo_keyword']);
            $saveInfo['seo_description'] = translation($value['seo_description']);
            $saveInfo['title'] = translation($value['title']);
            $saveInfo['content'] = translation($value['content']);
            $saveInfo['id'] = $value['id'];
            $saveInfo['status'] = 1;
            dump($saveInfo);die;
            D('Article')->save($saveInfo);
            showMsg($value['title']." --  翻译成功<br />","red", $ii);
            sleep(C(SLEEP_TIME));
        }
        G('end');
        showMsg("翻译完成! 总共翻译了".$ii."条数据，消耗了".G('begin','end').'s');
        sleep(C(SLEEP_TIME));

    }

    /**
     * 生成html
     */
    public function makeHtml(){
        //获取文章列表
        $limit = 100;
        
        $articles = D('Article')->where('status=1')->limit($limit)->select();

        //实时显示提示信息 html
        $ii = 0;
        G('begin');
        showMsgHtml();
        showMsg("准备生成文章!");
        
        foreach ($articles as $key => $value){
            
            $ii++;

            //获取友链
            $flinks = get_flinks($value['site_id']);
            $this->assign('flinks', $flinks);

            //检查目录文件
           
            $this->makeSiteDir($value['site_id']);
//            echo '检查目录OK';
            showMsg('检查目录OK','', $ii);
            sleep(C(SLEEP_TIME));

            //创建文章页面

            $this->makeArticleHtml($value['id']);
//            echo '创建文章OK';
            showMsg('创建文章OK','', $ii);
            sleep(C(SLEEP_TIME));

            //更新列表页面
            $this->makeListHtml($value['cid'], $value['site_id']);
            //echo '创建列表OK';
            showMsg('创建列表OK','', $ii);
            sleep(C(SLEEP_TIME));

            //更新首页
            $this->makeSiteHtml($value['site_id']);
            showMsg('更新首页OK','', $ii);
            sleep(C(SLEEP_TIME));
        }

        G('end');
        showMsg("全部完成！ 消耗了".G('begin','end').'s');
        sleep(C(SLEEP_TIME));

    }

    /**
     * 检查站点目录
     * @param $site_id
     */
    public function makeSiteDir($site_id){

        // 获取site信息
        $this->siteInfo = D('Site')->find($site_id);

        $SitePath = MAKE_SITE_PATH.$this->siteInfo['site'];

        // 创建site目录
        if(!is_dir($SitePath)) {
            mkdir($SitePath);
            showMsg($SitePath.'目录创建OK');
            sleep(C(SLEEP_TIME));
        }elseif(!is_writeable($SitePath)) {
            exit('目录 [ '.$this->siteInfo['site'].' ] 不可写！');
            showMsg($this->siteInfo['site'].'-- 目录不可写');
            sleep(C(SLEEP_TIME));
        }
        //创建全部本site下category目录
        $where = [
            'site_id' => $this->siteInfo['id'],
        ];

        $category = D('Category')->where($where)->select();
        foreach ($category as $key=>$cat){
            $categoryPath = $SitePath.'/'.$cat['dir'];

            if(!is_dir($categoryPath)) {
                mkdir($categoryPath);
                showMsg($categoryPath.'目录创建OK');
                sleep(C(SLEEP_TIME));

            }elseif(!is_writeable($categoryPath)) {
                exit('目录 [ '.$this->siteInfo['site'].'--'.$cat['name'].' ] 不可写！');
                showMsg($this->siteInfo['site'].'--'.$cat['name'].'-- 目录不可写');
                sleep(C(SLEEP_TIME));
            }
        }
    }

    /**
     * 创建文章
     * @param $artID
     */
    public function makeArticleHtml($artID){

        $articleInfo = D('Article')->find($artID);

        $categoryList = D('Category')->where('site_id = '.$articleInfo['site_id'])->select();
        $this->assign('categoryList', $categoryList);

        if($articleInfo['status'] < 0){
            showMsg($articleInfo['id'].'-- status 不正确');
            sleep(C(SLEEP_TIME));
        }else{
//            if($articleInfo['status'] == 0){
//                //文章需要翻译，执行翻译程序
//                $this->transArticle($articleInfo['id']);
//            }
         
            $savePath = get_category_dir_path($articleInfo['site_id'], $articleInfo['cid']);
            
            $articleInfo['time'] = date("Y-m-d H:i");
            $articleInfo['dir_name'] = get_category_dir_name($articleInfo['site_id'], $articleInfo['cid']);
            $articleInfo['cate_name'] = get_category_cate_name($articleInfo['site_id'], $articleInfo['cid']);

            $this->assign('article',$articleInfo);
            $this->assign('siteInfo',$this->siteInfo);

            $this->buildHtml('article_'.$articleInfo['id'].'.html',$savePath,$this->siteInfo['template'].'/article');
            showMsg($articleInfo['title'].'-- 生成成功', 'red');
            sleep(C(SLEEP_TIME));

            //更新站点信息
            $articleInfo['status'] = 10;
            $articleInfo['url'] = '/'.get_category_dir_name($articleInfo['site_id'], $articleInfo['cid']).'/article_'.$articleInfo['id'].'.html';
            D('Article')->save($articleInfo);

            //添加POST 数据
            $ret = $this->makePostUrl($articleInfo['id']);
            showMsg($ret,"red");
            sleep(C(SLEEP_TIME));
        }
    }

    /**
     * 更新分类列表
     * @param $cid
     * @param $site_id
     * @return string
     */
    public function makeListHtml($cid, $site_id){

        $this->assign('siteInfo', $this->siteInfo);

        $categoryList = D('Category')->where('site_id = '.$site_id)->select();
        $this->assign('categoryList', $categoryList);
        
        $map = [
            'cid' => $cid,
            'status' => 10,
            'site_id' => $site_id,
        ];

        $count = D('Article')->where($map)->count();
        $pageSize = 25;

        $i = ceil($count/$pageSize);
        $p = 1;
        while ($p <= $i){

            //分类列表显示
            $articleList = D('Article')->where($map)->page($p, $pageSize)->order('id DESC')->select(); //文章总数
            foreach($articleList as $key=>$value){
                $articleList[$key]['url'] = '/'.get_category_dir_name($site_id, $cid).'/article_'.$value['id'].'.html';
            }
            $this->assign('list', $articleList);
//            dump($articleList);die;
            //分页
            $url = 'list_';
            $page = listPage($count, $pageSize, $url, $p);
            $this->assign('page', $page);
            $res = $this->buildHtml('./'.'list_' . $p . '.html', get_category_dir_path($site_id, $cid) . '/', $this->siteInfo['template'].'/list');
            $p ++;
        }

        return $res;
    }


    /**
     * 更新站点首页
     * @param $site_id
     */
    public function makeSiteHtml($site_id){
        
        $this->assign('siteInfo', $this->siteInfo);

        //获取分类
        $categoryList = D('Category')->where('site_id = '.$site_id)->select();
        $this->assign('categoryList', $categoryList);
        
        $sitePath = get_site_dir_path($site_id);
        $this->buildHtml('index.html',$sitePath.'/',$this->siteInfo['template'].'/index');
//        \Think\Log::write($this->siteInfo['site'].' -- 更新首页成功','INFO');
        showMsg($this->siteInfo['site'].' -- 更新首页成功');
        sleep(C(SLEEP_TIME));
    }


    /**
     * 主动推送数据
     * @param int $id
     * @return string
     */
    public function makePostUrl($id=1){
        $urls[] = get_article_url($id);
        

        $api = 'http://data.zz.baidu.com/urls?site='.$this->siteInfo['domain_name'].'&token='.$this->siteInfo['baidu_post_token'];

        $ch = curl_init();
        $options =  array(
            CURLOPT_URL => $api,
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => implode("\n", $urls),
            CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
        );
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);
        // 获取推送成功条数和当天剩余推送条数
        $res = json_decode($result);
        $res = get_object_vars($res);
        if($res['success'] > 0){
            //插入数据
            //$this->addPostedUrl($postData);
            $ret = "插入成功，剩余".$res['remain'];
        }elseif($res['error'] > 0){
            $ret = "插入失败，错误原因".$res['message'];
        }

        return $ret;

    }
}